import { useResetState, useSetState } from "ahooks";
import { useEffect, useState } from "react";
import Taro, { useReachBottom, useRouter } from "@tarojs/taro";
import { PageContainer, Picker, View } from "@tarojs/components";
import dayjs from "dayjs";

import useList from "@/hooks/useList";
import ApiBudget from "@/api/budget";
import ByRow from "@/components/ui/ByRow";
import ByIcon from "@/components/ui/ByIcon";
import ByCell from "@/components/ui/ByCell";
import ByTabs from "@/components/ui/ByTabs";
import ByText from "@/components/ui/ByText";
import Card from "@/components/common/Card";
import Page from "@/components/common/Page";
import Moment from "@/components/app/Moment";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import FormInput from "@/components/common/FormInput";
import ProgressItem from "@/components/app/ProgressItem";
import PopupContainer from "@/components/app/PopupContainer";

import useForm from "@/hooks/useForm";

const tabList = [
  { label: "全部", value: "" },
  { label: "未通知", value: 0 },
  { label: "送货通知", value: 1 },
];

/**
 * BillMasterItem
 */
export interface BillMasterItem {
  /**
   * 附件金额
   */
  attachAmount: number;
  /**
   * 附件数量
   */
  attachCount: number;
  /**
   * 附件状态
   */
  attachStatus: string;
  /**
   * 单据分类名称
   */
  billClassName: string;
  /**
   * 订单ID
   */
  billMasterID: number;
  /**
   * 凭证编号
   */
  billNo: string;
  /**
   * 凭证图片数量
   */
  billPicCount: number;
  /**
   * 凭证类型 1-采购单 2-采购退货 3-销售 4-销售退货 5-调拨 6-调拨退货 7-移库 8 -入库 9-出库
   */
  billType: number;
  /**
   * 确认数量
   */
  confirmNum: number;
  /**
   * 是否冲销生成
   */
  isOffGenerate: boolean;
  /**
   * 供应商确认时间
   */
  mbpAcceptDate: string;
  /**
   * 材料商接收状态 0-未接收 1-部分接收 2-已接收 3-已驳回
   */
  mbpAcceptStatus: number;
  /**
   * 发货时间
   */
  mbpDeliverDate: string;
  /**
   * 发货状态 0-未发货 1-已发货
   */
  mbpDeliverStatus: number;
  /**
   * 供应商安装时间
   */
  mbpInstallDate: string;
  /**
   * 材料商安装状态 0-未安装 1-部分安装 2-已安装
   */
  mbpInstallStatus: number;
  /**
   * 部分确认数量
   */
  partialNum: number;
  /**
   * 下单日期
   */
  placeDate: string;
  /**
   * 下单状态 0-未下单 1-已下单
   */
  placeStatus: number;
  /**
   * 备注1
   */
  remark1: string;
  /**
   * 供应商名称
   */
  supplyName: string;
  /**
   * 总图片数量
   */
  totalPictureCount: number;
  /**
   * 未确认数量
   */
  unFirmNum: number;
  /**
   * 未上传数量
   */
  unUploadCount: number;
  /**
   * 工长确认状态 0-未确认 1-部分确认 2-全部确认
   */
  workerCheckedStatus: number;
  // [property: string]: any;
  /**
   * 是否需要安装
   */
  isMBPInStall: boolean;
}

const billTypeMap = {
  1: "采购单",
  2: "采购退货",
  3: "销售",
  4: "销售退货",
  5: "调拨",
  6: "调拨退货",
  7: "移库",
  8: "入库",
  9: "出库",
};

const PopupDate = ({
  billMasterID,
  onCancel,
  onSuccess,
}: {
  billMasterID: number;
  onCancel: () => void;
  onSuccess: () => void;
}) => {
  const { loading, model, setModel, submit } = useForm(
    ApiBudget.updateArrivalTime,
    {
      defaultModel: { billMasterID, deliveryDate: "" },
      rules: { deliveryDate: { required: true, message: "请选择到货时间" } },
      onSuccess() {
        Taro.showToast({ title: "操作成功！" });
        onSuccess();
      },
    }
  );

  return (
    <PopupContainer title="修改到货时间" onCancel={onCancel}>
      <View className="p-4">
        <ByCell label="到货时间" vertical>
          <Picker
            mode="date"
            className="w-full"
            value={model.deliveryDate}
            start={dayjs().format("YYYY-MM-DD")}
            onChange={(e) => setModel({ deliveryDate: e.detail.value })}
          >
            <FormInput
              disabled
              value={model.deliveryDate}
              placeholder="选择时间"
              suffix={
                <ByIcon name="Calendar" size={34} className="text-third" />
              }
            />
          </Picker>
        </ByCell>

        <ByButton
          className="my-3 w-[2/3]"
          size="large"
          loading={loading}
          onClick={submit}
        >
          提交
        </ByButton>
      </View>
    </PopupContainer>
  );
};

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const [search, setSearch] = useSetState({
    intentCustomerId,
    notifyDeliverStatus: "",
  });
  const { loading, list, nextPage, resetToFirst } = useList<BillMasterItem>(
    ApiBudget.materialConfirmList,
    { manual: true }
  );

  useEffect(() => {
    resetToFirst(search);
  }, [search]);

  useReachBottom(nextPage);

  const [selected, setSelected, resetSeleted] = useResetState<
    BillMasterItem | undefined
  >(undefined);
  const updateDate = (event, item) => {
    event.stopPropagation();
    setSelected(item);
  };

  return (
    <>
      <Page
        slotHeader={
          <View className="px-3 pb-3 bg-white">
            <ByTabs
              tabs={tabList}
              capsule
              active={search.notifyDeliverStatus}
              onChange={(e) => setSearch({ notifyDeliverStatus: e })}
            />
          </View>
        }
      >
        <ListView loading={loading} isEmpty={list.length === 0}>
          {list.map((item) => (
            <Card
              className="m-3"
              key={item.billMasterID}
              onClick={() =>
                Taro.navigateTo({
                  url: `detail?intentCustomerId=${intentCustomerId}&billMasterID=${item.billMasterID}&status=${item.workerCheckedStatus}`,
                })
              }
            >
              <ByRow content="between">
                <ByText bold size="lg">
                  {item.billNo}
                </ByText>
                <ByText size="sm" type="primary">
                  {billTypeMap[item.billType]}调拨开单
                </ByText>
              </ByRow>
              <ByText size="sm" type="third" className="mt-2">
                {item.supplyName}
              </ByText>

              <View className="mt-1">
                <ProgressItem
                  tag
                  text="下单"
                  status={
                    item.workerCheckedStatus === 2 || item.placeStatus === 1
                      ? "success"
                      : undefined
                  }
                />
                <ProgressItem
                  tag
                  text="接收"
                  status={
                    item.mbpAcceptStatus == 3
                      ? "error"
                      : item.workerCheckedStatus === 2 ||
                        item.mbpAcceptStatus == 2
                      ? "success"
                      : item.mbpAcceptStatus == 1
                      ? "active"
                      : undefined
                  }
                />
                <ProgressItem
                  tag
                  text="发货"
                  status={
                    item.workerCheckedStatus === 2 || item.mbpDeliverStatus == 1
                      ? "success"
                      : undefined
                  }
                />

                {item.isMBPInStall && (
                  <ProgressItem
                    tag
                    text="安装"
                    status={
                      item.workerCheckedStatus === 2 ||
                      item.mbpInstallStatus === 2
                        ? "success"
                        : item.mbpInstallStatus === 1
                        ? "active"
                        : undefined
                    }
                  />
                )}

                <ProgressItem
                  tag
                  tail
                  text="到货"
                  status={
                    item.workerCheckedStatus === 2
                      ? "success"
                      : item.workerCheckedStatus === 1
                      ? "active"
                      : undefined
                  }
                />
              </View>

              <ByText size="xs" type="third" className="mt-2">
                <Moment value={item.placeDate} /> 下单
              </ByText>

              <ByRow content="between" align="center" className="mt-2">
                <ByText size="xs" type="third" className="mt-2">
                  附加费：{item.attachAmount}
                </ByText>
                {item.mbpAcceptStatus !== 2 && (
                  <ByButton
                    size="small"
                    className="mr-0"
                    onClick={(event) => updateDate(event, item)}
                  >
                    修改到货时间
                  </ByButton>
                )}
              </ByRow>
            </Card>
          ))}
        </ListView>
      </Page>

      <PageContainer round show={!!selected} onLeave={resetSeleted}>
        {selected && (
          <PopupDate
            billMasterID={selected?.billMasterID}
            onCancel={resetSeleted}
            onSuccess={() => (resetSeleted(), resetToFirst(search))}
          />
        )}
      </PageContainer>
    </>
  );
};
